package com.simplehire.service.impl;

import com.simplehire.service.InterviewService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class InterviewServiceImpl implements InterviewService {

    private final RestTemplate restTemplate;

    @Value("${deepseek.api.key:default-key}")
    private String deepseekApiKey;

    @Value("${deepseek.api.url:https://api.deepseek.com/v1/chat/completions}")
    private String deepseekApiUrl;

    @Value("${tongyi.api.key:default-key}")
    private String tongyiApiKey;

    @Value("${tongyi.api.url:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation}")
    private String tongyiApiUrl;

    @Value("${douban.api.key:default-key}")
    private String doubanApiKey;

    @Value("${douban.api.url:https://open.bigmodel.cn/api/paas/v4/chat/completions}")
    private String doubanApiUrl;

    public InterviewServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public String generateInterviewResult(String resumeText, String aiModel) {
        return generateAIResponse(
                aiModel,
                "分析这份简历：" + resumeText.substring(0, Math.min(resumeText.length(), 1000)),
                "模拟AI分析结果：\n" +
                        "1. 简历内容长度：" + resumeText.length() + "字符\n" +
                        "2. 关键技能提取：[Java, Spring Boot, MySQL, React]\n" +
                        "3. 工作经验：3年\n" +
                        "4. 匹配度评分：85/100\n" +
                        "5. 建议考察点：项目架构设计、技术深度、团队协作能力"
        );
    }

    @Override
    public String generateInterviewQuestions(String jobDescription, String resumeText, String aiModel) {
        String content = "根据职位描述：" + jobDescription +
                " 和简历内容：" + resumeText.substring(0, Math.min(resumeText.length(), 500)) +
                " 生成5个专业的面试问题";

        return generateAIResponse(
                aiModel,
                content,
                "模拟面试问题：\n" +
                        "1. 请详细介绍您在过去项目中使用Spring Boot的技术架构和遇到的挑战\n" +
                        "2. 您如何设计一个高并发的系统来应对大量用户请求？\n" +
                        "3. 请分享一个您解决复杂技术问题的具体案例\n" +
                        "4. 在团队协作中，您如何协调不同成员之间的技术分歧？\n" +
                        "5. 您如何看待当前行业的最新技术趋势，并如何保持技术更新？"
        );
    }

    @Override
    public String chatWithAI(String question, String context, String aiModel) {
        String content = "基于以下所有信息进行回答，保持对话连贯性：\n" +
                "上下文信息：" + context + "\n" +
                "当前问题：" + question + "\n" +
                "请给出简洁、专业的回答，直接回应问题，不要重复上下文内容。";

        return generateAIResponse(
                aiModel,
                content,
                "模拟AI回答：\n针对您提出的关于\"" + question + "\"的问题，根据上下文信息，建议从以下方面考虑：\n" +
                        "1. 结合简历中的相关经验进行分析\n" +
                        "2. 考虑职位需求与个人技能的匹配点\n" +
                        "3. 可以进一步提供具体案例来支撑您的回答"
        );
    }

    private String generateAIResponse(String aiModel, String content, String mockResult) {
        String apiKey;
        String apiUrl;

        switch (aiModel.toLowerCase()) {
            case "tongyi":
                apiKey = tongyiApiKey;
                apiUrl = tongyiApiUrl;
                break;
            case "douban":
                apiKey = doubanApiKey;
                apiUrl = doubanApiUrl;
                break;
            case "deepseek":
            default:
                apiKey = deepseekApiKey;
                apiUrl = deepseekApiUrl;
                break;
        }

        // 当API密钥未配置时返回模拟结果
        if (apiKey.equals("default-key") || apiKey.isEmpty()) {
            return "【" + getModelDisplayName(aiModel) + "】" + mockResult;
        }

        try {
            Map<String, Object> request = createApiRequest(aiModel, content);
            HttpHeaders headers = createApiHeaders(aiModel, apiKey);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(request, headers);

            Map<String, Object> response = restTemplate.postForObject(
                    apiUrl,
                    requestEntity,
                    Map.class
            );

            if (response == null) {
                return "【" + getModelDisplayName(aiModel) + "】API调用返回空响应，请检查网络连接或API配置";
            }

            return "【" + getModelDisplayName(aiModel) + "】" + parseApiResponse(aiModel, response);

        } catch (HttpClientErrorException e) {
            return "【" + getModelDisplayName(aiModel) + "】客户端错误：" + e.getStatusCode() + " - " + e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            return "【" + getModelDisplayName(aiModel) + "】服务器错误：" + e.getStatusCode() + " - " + e.getResponseBodyAsString();
        } catch (Exception e) {
            return "【" + getModelDisplayName(aiModel) + "】生成AI响应失败：" + e.getMessage();
        }
    }

    private Map<String, Object> createApiRequest(String aiModel, String content) {
        Map<String, Object> request = new HashMap<>();

        switch (aiModel.toLowerCase()) {
            case "tongyi":
                request.put("model", "qwen-max");
                request.put("input", Map.of("messages", List.of(
                        Map.of("role", "user", "content", content)
                )));
                request.put("parameters", Map.of(
                        "temperature", 0.7,
                        "max_tokens", 2000
                ));
                break;
            case "douban":
                // 修复豆包模型请求格式
                request.put("model", "doubao-seed-1-6-flash-250828");  // 豆包可用模型
                request.put("messages", List.of(
                        Map.of("role", "user", "content", content)
                ));
                request.put("temperature", 0.7);
                request.put("max_tokens", 2000);
                break;
            case "deepseek":
            default:
                request.put("model", "deepseek-chat");
                request.put("messages", List.of(
                        Map.of("role", "user", "content", content)
                ));
                request.put("temperature", 0.7);
                request.put("max_tokens", 2000);
                break;
        }

        return request;
    }

    private HttpHeaders createApiHeaders(String aiModel, String apiKey) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        switch (aiModel.toLowerCase()) {
            case "tongyi":
                headers.set("Authorization", "Bearer " + apiKey);
                break;
            case "douban":
                headers.set("Authorization", "Bearer " + apiKey);
                break;
            case "deepseek":
            default:
                headers.set("Authorization", "Bearer " + apiKey);
                break;
        }

        return headers;
    }

    private String parseApiResponse(String aiModel, Map<String, Object> response) {
        try {
            switch (aiModel.toLowerCase()) {
                case "tongyi":
                    if (response.containsKey("output")) {
                        Map<?, ?> outputMap = (Map<?, ?>) response.get("output");
                        if (outputMap.containsKey("text")) {
                            return outputMap.get("text").toString();
                        }
                    }
                    break;
                case "douban":
                    // 修复豆包响应解析
                    if (response.containsKey("choices")) {
                        List<?> choices = (List<?>) response.get("choices");
                        if (!choices.isEmpty()) {
                            Map<?, ?> choiceMap = (Map<?, ?>) choices.get(0);
                            Map<?, ?> messageMap = (Map<?, ?>) choiceMap.get("message");
                            return messageMap.get("content").toString();
                        }
                    }
                    break;
                case "deepseek":
                default:
                    if (response.containsKey("choices")) {
                        List<?> choices = (List<?>) response.get("choices");
                        if (!choices.isEmpty()) {
                            Map<?, ?> choiceMap = (Map<?, ?>) choices.get(0);
                            Map<?, ?> messageMap = (Map<?, ?>) choiceMap.get("message");
                            return messageMap.get("content").toString();
                        }
                    }
                    break;
            }
            return "无法解析API响应: " + response.toString();
        } catch (Exception e) {
            return "解析响应失败: " + e.getMessage();
        }
    }

    private String getModelDisplayName(String aiModel) {
        switch (aiModel.toLowerCase()) {
            case "tongyi":
                return "通义千问";
            case "douban":
                return "豆包";
            case "deepseek":
                return "DeepSeek";
            default:
                return "AI模型";
        }
    }
}